<template>
    <div>
        <div class="mt14" v-if="importTemplate.widgetList.length" v-loading="formloading" style="position: relative;">
          <div style="margin-top:40px;" v-if="pagestatus==1">
            <VFormRender v-if="drawer"
           ref="preForm"
           :form-json="importTemplate"
           :form-data="testFormData"
           :preview-state="true"
           :option-data="testOptionData"
           :global-dsv="designerDsv"
           :index-flag="indexflag"
         >
         </VFormRender>
         </div>
         <!-- from-foot-btn fix -->
         <div class="button fixnew btn-shadow">
           <el-button size="mini" type="primary" :loading="loading" @click="saveFn">保存</el-button>
         </div>
          <div class="" style="margin-top:40px;" >
              <FormTable ref="wulidangan" :flagStatu="flagStatu" :treeData="treeData" :pagestatus="pagestatus" :keyName="keyName" :testFormData="testFormData" :id="id" :typeid="wltypeid" :isSubmit="isSubmit"  :formDataAll="formDataAll" @handlerisSubmit="handlerisSubmit"></FormTable>
          </div>
        </div>
        <div v-else>
          <default-page :index="16" :min-height="420" />
        </div>
    </div>
  </template>
  <script>
  import VFormRender from '@/components/form-render/index'
  import defaultPage from '@/components/common/defaultPage'
  import { crudModuleCreateApi, crudModuleSaveDataApi, crudModuleUpdateApi, crudFangkeSaveApi, crudFangkeuserCreateApi, crudModuleBatchDelApi,
    crudForminsertDataAllApi, putUpdateFieldApi 
   } from '@/api/develop'
  import { FacialVerificationApi } from '@/api/enterprise'
  import { CLOSE_NODE_ICON_TOOLBAR } from '@/components/xmind-editor/event-constant'
  import ApiUrl from '@/api/apiUrls' // dengshunbo 2024-12-27新增
  import FormTable from '@/components/detailsEdit/formtable.vue'
import { pages } from '@/views/business/components/formSetting/components/form-create-designer/vue.config'
  export default {
    name: '',
    components: { VFormRender, defaultPage, FormTable },
    props: {
      keyName: {
        type: String,
        default: ''
      },
      crud: {
        type: Object,
        default: () => {}
      },
      pagestatus: {
         type: Number,
         default: 1
      },
      treeData: {
         type: [Array, Object],
         default: () => []
      },
    
     
    },
    data() {
      return {
        drawer: false,
        isSubmit: 0,
        importTemplate: {
          formConfig: {},
          widgetList: []
        },
        title: '新增',
        id: 0, // 当前列表的id值
        designer: {},
        testFormData: {},
        loading: false,
        testOptionData: {
          select62173: [],
          select001: []
        },
        formloading: false,
        drawerData:{},
        indexflag: 1,
        wltypeid: 0,
       
        formdatasubmit:{},
        isFlage: false,
        flagStatu: 0,
        formDataAll: [
            {
                name: '规格',
                value: 'leibieguigebiao',
                datadictname:'',
                tableHeader:[], // 表格头部信息
                tableData:[], // 表格数据
                deleteData:[], // 要删除的表格数据
                selectData:[], // 选中数据
                datadictList:{},
                istable: true,
                subitem:[{
                  name:'添加',
                  icon: 'el-icon-plus',
                  index: 1,
                  value: 'add',
                  tablename:'guige'
                  },
                  
                  {
                  name:'删除',
                  icon: 'el-icon-delete',
                  index: 3,
                  value: 'delete'
                  },
                 ],
                search: { // 搜索
                   page: 1,
                   limit: 100,
                   is_system: 1,
                   is_field_all: 1,
                   order_by: {},
                   scope_frame: 'all',
                   show_search_type: '0',
                   view_search: [],
                   view_search_boolean:''
                },
                form: { // 表单

                }
            },
           
        ],
       
       
      }
    },
    computed: {
      designerDsv() {
        return this.globalDsv
      }
    },
    mounted() {
       if(this.keyName == 'gongxushezhong'){
           this.formDataAll[0].name = '子工序模版'
           this.formDataAll[0].value = 'zigongxu'
           this.formDataAll[0].subitem[0].tablename = 'zigongxushezhi'
       }
    }, 
    methods: {
      async openBox(id, data, index=1, item='') {
        console.log("module-wlForm:", id, data, index, item)
        this.drawer = false;
        this.id = id || 0;
        if (id) {
          this.drawerData = data; // dengshunbo 2025-3-17 获取查看详情数据
          if(data.module_info && data.module_info.item_sn){
            this.wltypeid = data.module_info.item_sn.id;
          }
        } else {
          this.$set(this, 'testFormData', {})
        }
        let obj = {}
        if (this.crud) {
          obj.crud_id = this.crud.crud_id
          obj.crud_value = this.crud.crud_value
        } else {
          obj = {}
        }
        obj.id = this.id
        const res = await crudModuleCreateApi(this.keyName, obj)
        if (res.data.form_info && res.data.form_info.global_options) {
          this.$set(this.importTemplate, 'formConfig', res.data.form_info.global_options)
        }
        this.$set(this.importTemplate, 'widgetList', res.data.form_info.options)
        // dengshunbo 2025-1-20 改
        if (data && index != 11) { // 正常数据处理
          // dengshunbo 2025-1-20
          if(this.keyName=="fangkeguanli"){
            if(data.module_info.shouquanmenjinzu){
               let meji = data.module_info.shouquanmenjinzu.split(",")
               data.module_info.shouquanmenjinzu = meji;
            }else{
               data.module_info.shouquanmenjinzu = ''
            }
            this.$set(this, 'testFormData', data.module_info)
          }else{
            this.$set(this, 'testFormData', data.module_info)
          }
        }else if(this.keyName == 'wuliaoleibieshuxing'){ // 添加子级数据处理
          this.$set(this, 'testFormData', {fuwuliaoleibie: data.leibiedaima})
        }else if(this.keyName == 'gongxushezhong') {
          this.$set(this, 'testFormData', {fugongxudaima: data.gongxudaima})
        }
      
        this.drawer = true
        this.isSubmit = 1;
       
      
      },
      handlerisSubmit(){
         this.isSubmit = 0;
      },
      saveFn() {
        if(this.pagestatus==2){
          this.handlerWLQDSaveTabelFilter(this.id);
          return;
        }
        this.$refs['preForm']
          .getFormData()
          .then((formData) => {
            this.formdatasubmit = formData;
            if (this.id > 0) { // 编辑
              // dengshunbo 2025-3-17
              if(this.keyName=="fangkeguanli"){
                this.formloading = true;
                if(formData.face_thumb.length == 0){
                   formData.face_thumb  = ''
                }
                if(formData.face_thumb){
                  let faceData = {face_thumb:  formData.face_thumb[0].url} // 实拍图效验form数据
                  if(this.drawerData.module_info.face_thumb && this.drawerData.module_info.face_thumb.length > 0){ // 判断是否有编辑前是否存在实拍头像
                      if(this.drawerData.module_info.face_thumb[0].url != faceData.face_thumb){ // 判断实拍头像是否有变化
                        this.handlerFacialVerification(faceData, formData, this.id)
                      }else{ // 没有变化直接调用更新接口
                        if(formData.shouquanmenjinzu){
                            let meji = formData.shouquanmenjinzu.join(",")
                            formData.shouquanmenjinzu = meji
                        }else{
                            formData.shouquanmenjinzu = ''
                        }
                        this.upladData(this.id, formData)
                      }
                  }else{ // 新增时没有添加实拍头像，编辑时已加入进行人脸效验
                    this.handlerFacialVerification(faceData, formData, this.id)
                  }
                }else{ // 编辑时未提交实拍头像-直接调用更新接口
                  if(formData.shouquanmenjinzu){ // 对授权门禁组数据进行处理后提交
                      let meji = formData.shouquanmenjinzu.join(",")
                      formData.shouquanmenjinzu = meji
                  }else{
                      formData.shouquanmenjinzu = ''
                  }
                  this.upladData(this.id, formData)
                }
                // end
              }else{ // 员代码
                this.upladData(this.id, formData)
                this.handlerSaveTabelFilter(this.id);
              }
            } else {
              // dengshunbo 2025-1-14 访客新增调后台接口
              if(this.keyName=="fangkeguanli"){
                this.formloading = true;
                if(formData.face_thumb.length == 0){
                   formData.face_thumb  = ''
                }
                let userinfoobj = JSON.parse(localStorage.getItem('userInfo'));
                formData.yaoqingrenxingming = userinfoobj.name
                if(formData.face_thumb){
                  let faceData = {face_thumb:  formData.face_thumb[0].url}
                   this.handlerFacialVerification(faceData, formData)
                }else{
                  if(formData.shouquanmenjinzu){
                      let meji = formData.shouquanmenjinzu.join(",")
                      formData.shouquanmenjinzu = meji
                  }else{
                      formData.shouquanmenjinzu = ''
                  }
                  this.savaData(formData)
                }
              }else{
                // 原代码
                this.formdatasubmit = formData;
                this.savaData(formData)
                
              }
            }
          })
          .catch((error) => {
            this.$message.error(error)
          })
      },
      // 调用关联表数据进行处理保存
      async handlerSaveTabelFilter(saveid){ 
        let formTabledata = this.$refs.wulidangan.formtable;
        let userinfo = JSON.parse(localStorage.getItem('userInfo'));
        for(let i=0;i<formTabledata.length;i++){
            if(formTabledata[i].istable){
              let tabledata2 = formTabledata[i].tableData;
              let addData = [];
              if(tabledata2.length > 0){
                for(let j=0;j<tabledata2.length;j++){
                  if(!tabledata2[j].id){ // 物料类别
                    let formdata2 = JSON.parse(JSON.stringify(tabledata2[j]))
                    // 批量保存
                    if(tabledata2[j].zhuangtai){
                      let imdata = formTabledata[i].datadictList.zhuangtai;
                        for(let i=0;i<imdata.length;i++){
                          if(tabledata2[j].zhuangtai == imdata[i].value || tabledata2[j].zhuangtai == imdata[i].name ){
                            formdata2.zhuangtai = '/'+imdata[i].value+'/';
                          }
                        }
                     }
                     if(tabledata2[j].laiyuan){
                      let imdata = formTabledata[i].datadictList.laiyuan;
                        for(let i=0;i<imdata.length;i++){
                          if(tabledata2[j].laiyuan == imdata[i].value || tabledata2[j].laiyuan == imdata[i].name ){
                            formdata2.laiyuan = '/'+imdata[i].value+'/';
                          }
                        }
                     }
                     delete formdata2.disabled;
                     if(tabledata2[j].wuliaoleibiebianmaid == ''){
                        formdata2.wuliaoleibiebianmaid = saveid; 
                     }
                     if(tabledata2[j].gongxudaimaid){
                        formdata2.fugongxu = saveid;
                        formdata2.gongxudaima = tabledata2[j].gongxudaimaid; 
                        delete formdata2.gongxudaimaid
                     }
                     formdata2.user_id = userinfo.id;
                     addData.push(formdata2)
                    //  end
                    //  单个保存
                    //  tabledata2[j].wuliaoleibiebianmaid = {id: saveid, name: this.formdatasubmit.item_sn};
                    //  await crudModuleSaveDataApi(formTabledata[i].value, tabledata2[j], true); // 保存
                    // end
                  }else{  // 编辑
                    let formdata3 = JSON.parse(JSON.stringify(tabledata2[j]))
                    if(formTabledata[i].value == 'zigongxu'){
                      if(tabledata2[j].zhuangtai){
                        let imdata = formTabledata[i].datadictList.zhuangtai;
                        for(let i=0;i<imdata.length;i++){
                          if(tabledata2[j].zhuangtai == imdata[i].value || tabledata2[j].zhuangtai == imdata[i].name ){
                              formdata3.zhuangtai = [imdata[i].value];
                          }
                        }
                      }
                      if(tabledata2[j].laiyuan){
                        let imdata = formTabledata[i].datadictList.laiyuan;
                        for(let i=0;i<imdata.length;i++){
                          if(tabledata2[j].laiyuan == imdata[i].value || tabledata2[j].laiyuan == imdata[i].name ){
                              formdata3.laiyuan = [imdata[i].value];
                          }
                        }
                      }
                      if(tabledata2[j].fugongxu){
                        formdata3.fugongxu = {id: saveid, name: tabledata2[j].fugongxu}
                      }
                      if(tabledata2[j].gongxudaima){
                          formdata3.gongxudaima = {id: tabledata2[j].id, name: tabledata2[j].gongxudaima}
                      }
                    }
                    await crudModuleUpdateApi(formTabledata[i].value, tabledata2[j].id,formdata3, true)
                  }
                }
              }

              // 批量删除操作
              let deleteData = formTabledata[i].deleteData;
              if(deleteData.length > 0){
                 await crudModuleBatchDelApi(formTabledata[i].value, {ids: deleteData}, true);
              }

               // 添加的数据进行批量添加
              if(addData.length > 0){
                let objss = { table: formTabledata[i].value, data: encodeURI(JSON.stringify(addData))  }
                await crudForminsertDataAllApi(objss)
               
              }
            }
        }
        
      },
      async handlerPutFieldUpdatevision(id){
           putUpdateFieldApi('wuliaoxinxi', id, {field_name: 'bomm_ver', value: '2'})
      },
      // 物料清单关联表数据进行处理保存
      async handlerWLQDSaveTabelFilter(saveid){
        let formTabledata = this.$refs.wulidangan.formtable;
        let userinfo = JSON.parse(localStorage.getItem('userInfo'));
        for(let i=0;i<formTabledata.length;i++){
            if(formTabledata[i].istable){
              let tabledata2 = formTabledata[i].tableData;
              let addData = [];
              if(tabledata2.length > 0){
                for(let j=0;j<tabledata2.length;j++){
                      // tabledata2[j].fuwuliaobianmaid = {}
                      let formdata2 = []
                      if(tabledata2[j].id==''){
                          formdata2 = JSON.parse(JSON.stringify(tabledata2[j]))
                          formdata2.fuwuliaobianmaid = saveid;//{id: saveid, name: this.treeData[0].item_sn}
                          formdata2.user_id = userinfo.id;
                          // formdata2.wuliaobianmaid = tabledata2[j].wuliaobianmaid;// {id: tabledata2[j].wuliaobianmaid, name: tabledata2[j].item_sn}
                          delete formdata2.children;
                          delete formdata2.dananid;
                          delete formdata2.label;
                          delete formdata2.labels;
                          delete formdata2.name;
                          delete formdata2.zhongwenmiaoshu;
                          delete formdata2.unit;
                          delete formdata2.item_sn;
                          delete formdata2.item_depc;
                          delete formdata2.id;
                          delete formdata2.disabled;
                          addData.push(formdata2)
                         
                        //  await crudModuleSaveDataApi(formTabledata[i].value, formdata2, true);
                      }else{
                          let formdata2 = {}
                          formdata2.beizhu = tabledata2[j].beizhu || ''
                          formdata2.dahuodingliao = tabledata2[j].dahuodingliao
                          formdata2.dahuoquedingriqi = tabledata2[j].dahuoquedingriqi
                          formdata2.fuwuliaobianmaid = {id: saveid, name: this.treeData[0].item_sn}
                          formdata2.wuliaobianmaid = {id: tabledata2[j].wuliaobianmaid, name: tabledata2[j].item_sn}
                          formdata2.jishu = tabledata2[j].jishu
                          formdata2.sunhao = tabledata2[j].sunhao
                          formdata2.shiyongbumen = {id: tabledata2[j].shiyongbumen, name: ''}
                          formdata2.sunhaodaima = tabledata2[j].sunhaodaima
                          if(tabledata2[j].sunhaoleixing){
                            formdata2.sunhaoleixing = this.handlerRplace(tabledata2[j].sunhaoleixing)
                          }else{
                            formdata2.sunhaoleixing = []
                          }
                          formdata2.wuliaodanganid = tabledata2[j].wuliaodanganid
                          formdata2.yangbandingliao = tabledata2[j].yangbandingliao
                          formdata2.yangbanquedingriqi = tabledata2[j].yangbanquedingriqi
                          formdata2.yongliang = tabledata2[j].yongliang
                          await crudModuleUpdateApi(formTabledata[i].value, tabledata2[j].id, formdata2, true)
                        
                    }
                }
              
              }

             

              // await crudForminsertDataAllApi()
              let deleteData = formTabledata[i].deleteData;
              if(deleteData.length > 0){ // 删除
                await crudModuleBatchDelApi(formTabledata[i].value, {ids: deleteData}, true);
              }
              // 添加的数据进行批量添加
              if(addData.length > 0){
                let objss = { table: formTabledata[i].value, data: encodeURI(JSON.stringify(addData))  }
                let resdata1 = await crudForminsertDataAllApi(objss)
                if(i == 0){
                   this.$message.success("添加保存成功")
                }
              }           
            }
        }
        this.handlerPutFieldUpdatevision(saveid);
      
      },
      handlerRplace(val){
        if(val.includes("/")){
          let newStr = val.replace(/\//g, "");
          return newStr
        }else{
          return val;
        }
      },
      // 关联物料档案实体表保存接口
      handlersaveData(keyName, data){
        crudModuleSaveDataApi(keyName, data, true)
          .then((res) => {
            if (res.status == 200) {
              
            }
          })
          .catch((err) => {
            this.loading = false
          })
      },
      // 关联物料档案实体表删除接口
      handlerDeleteData(keyName, data){
        crudModuleBatchDelApi(keyName, data, true)
          .then((res) => {
            if (res.status == 200) {
              
            }
          })
          .catch((err) => {
            this.loading = false
          })
      },
      // 实体列表新增保存
      savaData(data) {
        this.loading = true
        if (this.crud) {
          data.crud_id = this.crud.crud_id
          data.crud_value = this.crud.crud_value
        }
        let imgurlArr = this.$refs.wulidangan.imageUrl || ''; //图片
        if(imgurlArr && imgurlArr.length > 0){
           data.imaurl = imgurlArr
        }
        
        // dengshunbo 2025-1-14 访客新增调后台接口
        if(this.keyName == 'fangkeguanli'){ 
          this.formloading = false;
          data.yaoqinglianjie = "";
          crudFangkeSaveApi(data)
          .then((res) => {
              if (res.status == 200) {
                 // 调用修改生成访客邀请链接接口
                  const key = 12345999;
                  let dids = this.encrypt(res.data.id, key)
                  let yaoqinglianjie = ApiUrl + "/work/visitor/index.html?id="+dids;
                  data.yaoqinglianjie = yaoqinglianjie;
                  this.FKupladData(res.data.id, data);// 生产邀请链接
                  // end
                  // 访客是否下发授权
                  if(data.daofangzhuangtai==2 && data.shoujihaoma){ // 访客状态为访客 且 手机号码不为空
                    if(data.face_thumb.length > 0){ // 访客头像不为空
                       this.getFkUserCreate(res.data.id) // 访客下发授权接口
                    }
                  }
              }else{
                 this.$message.error(res.message)
              }
              this.loading = false
            })
            .catch((err) => {
              this.loading = false
            })
          // end
        }else{ // 非访客管理调用原代码
          // 原代码
          crudModuleSaveDataApi(this.keyName, data)
          .then((res) => {
            if (res.status == 200) {
              this.handleClose()
              
              let saveid = res.data.id;
              this.handlerSaveTabelFilter(saveid)
              this.isSubmit = 0;
              this.$emit('getList', res.data.id)
            }
            this.loading = false
          })
          .catch((err) => {
            this.loading = false
          })
        }
      },
      // dengshunbo 2025-1-14 访客新增调后台接口
      handlerFacialVerification(faceobj, formdata, id=0){
        FacialVerificationApi(faceobj).then((res)=>{
          if(res.data.code==200){
             if(res.data.data){
                if(formdata.shouquanmenjinzu){
                    let meji = formdata.shouquanmenjinzu.join(",")
                    formdata.shouquanmenjinzu = meji
                }else{
                  formdata.shouquanmenjinzu = ''
                }
                if(id==0){
                  this.savaData(formdata)
                }else{
                  this.upladData(this.id, formdata)
                }
             }else{
                this.$message.error("实拍头像识别失败,请检查头像是否清晰或正确")
             }
          }else{
            this.$message.error(res.data.message)
          }
        }).catch((err)=>{
          if(err.data.code==200){
             if(err.data.data){
                if(formdata.shouquanmenjinzu){
                    let meji = formdata.shouquanmenjinzu.join(",")
                    formdata.shouquanmenjinzu = meji
                }else{
                  formdata.shouquanmenjinzu = ''
                }
                if(id==0){
                  this.savaData(formdata)
                }else{
                  this.upladData(this.id, formdata)
                }
             }else{
                this.formloading = false;
                this.$message.error("实拍头像识别失败,请检查头像是否清晰或正确")
             }
          }else{
            this.formloading = false;
            this.$message.error(err.data.message)
          }
        })
      },
      // 访客更新添加邀请链接
      FKupladData(id, data){
        let dataobj = {}
        if (this.crud) {
          dataobj.crud_id = this.crud.crud_id
          dataobj.crud_value = this.crud.crud_value
        }
        dataobj.yaoqinglianjie = data.yaoqinglianjie;
        crudModuleUpdateApi(this.keyName, id, data)
          .then((res) => {
            if (res.status == 200) {
              this.handleClose()
              this.$emit('getList')
            }
          })
          .catch((err) => {
            this.loading = false
          })
      },
      encrypt(num, key=12345999) {
          return num * key;
      },
      // 访客下发授权接口
      getFkUserCreate(id){
        crudFangkeuserCreateApi(id).then((res)=>{
           
        }).catch((err)=>{
           
        })
      },
      // end
      // 实体列表更新保存
      upladData(id, data) {
        this.loading = true
        if (this.crud) {
          data.crud_id = this.crud.crud_id
          data.crud_value = this.crud.crud_value
        }
        if(this.keyName=="fangkeguanli"){
          this.formloading = false;
          const key = 12345999;
          let dids = this.encrypt(id, key)
          let yaoqinglianjie = ApiUrl + "/work/visitor/index.html?id="+dids;
          data.yaoqinglianjie = yaoqinglianjie;
        }
        let imgurlArr = this.$refs.wulidangan.imageUrl || ''; //图片
        if(imgurlArr && imgurlArr.length > 0){
           data.imaurl = imgurlArr
        }
        // 原代码
        crudModuleUpdateApi(this.keyName, id, data)
          .then((res) => {
            if (res.status == 200) {
              this.isSubmit = 0;
              if(this.keyName == 'fangkeguanli'){
                 // 访客是否下发授权
                  if(data.daofangzhuangtai==2 && data.shoujihaoma){ // 访客状态为访客 且 手机号码不为空
                    // if(data.face_thumb.length > 0){ // 访客头像不为空
                      let jhtime = this.hadnlerFilterReturn(data.jihuadaofangriqi) // 计划到访日期时间戳
                      let sjtime = this.hadnlerFilterReturn(); // 当前日期时间戳
                      if(jhtime < sjtime)
                        this.getFkUserCreate(id) // 访客下发授权接口
                    // }
                  }
                  this.$emit('getList')
              }else{
                this.$emit('getList', id)
              }
            }
            this.loading = false
          })
          .catch((err) => {
            this.loading = false
          })
        
      },
  
      handleClose() {
        // this.$refs['preForm'].resetForm()
        this.drawer = false
        this.id = 0
        this.isSubmit = 0;
      },
      // dengshunbo 2025-1-14 时间戳转换
      hadnlerFilterReturn(time=''){
        let rtime = ''
        if(time){
          rtime = new Date(time).getTime();
        }else{
          rtime = new Date().getTime();
        }
        return rtime;
      },

     
      
    }
  }
  </script>
  <style scoped lang="scss">
  /deep/.el-drawer__body {
    padding: 10px 20px 50px 20px;
  }
  .p10 {
    width: 100%;
    padding: 0 10px;
  }
  .fixnew{
    position: absolute;
    top:-42px;left:0;
  }
  /deep/ .el-tabs__header .el-tabs__item{
    line-height:40px!important;
  }
  /deep/ .el-upload--picture-card{
    width:100px;height:100px;line-height: 100px;
  }
  </style>
  